﻿using ERPPublic;
using ERPPublic.eneity;
using MediatR;
using Newtonsoft.Json;
using ProcurementManagement.Applcation.Command.ProcurementReturnCommand;
using ProcurementManagement.Domain.Dtos;
using ProcurementManagement.Domain.ProcurementDomain;
using ProcurementManagement.Dtos;
using SqlSugar;
using static ERPPublic.ParseAPI;
using static ProcurementManagement.Applcation.CommandHanlers.ProcurementReturnCommandHandler.FanProcurementReturnCommandHandler;

namespace ProcurementManagement.Applcation.CommandHanlers.ProcurementReturnCommandHandler
{
    public class ListProcurementReturnCommandHandler : IRequestHandler<ListProcurementReturnCommand, PageDto<ListProcurementReturnDto>>
    {
        ISqlSugarClient db;

        public ListProcurementReturnCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        async Task<PageDto<ListProcurementReturnDto>> IRequestHandler<ListProcurementReturnCommand, PageDto<ListProcurementReturnDto>>.Handle(ListProcurementReturnCommand request, CancellationToken cancellationToken)
        {
            List<Products> products = await GetProductList("", "", 1, 1000);

            var vendorData = db.Queryable<Vendor>()
                .InnerJoin<PurchaseReturns>((v, pr) => v.VName == pr.VName)
                .InnerJoin<ReturnProduct>((v, pr, rp) => pr.PurchaseReturnsCode == rp.PurchaseReturnsCode)
                .Where((v, pr, rp) => v.IsDel == false && pr.PurchaseReturnsCode == rp.PurchaseReturnsCode)
                .Select((v, pr, rp) => new ListProcurementReturnDto
                {
                    VName = v.VName,
                    PurchaseReturnsIds = pr.PurchaseReturnsIds,
                    PurchaseReturnsCode = pr.PurchaseReturnsCode,
                    PurchaseReturnsTopic = pr.PurchaseReturnsTopic,
                    PReturnsPersonnel = pr.PReturnsPersonnel,
                    ManpowerId = pr.ManpowerId,
                    PRReturnDate = pr.PRReturnDate,
                    PROutboundProgress = pr.PROutboundProgress,
                    PRShipmentState = pr.PRShipmentState,
                    PRReturnType = pr.PRReturnType,
                    RPNum = rp.RPNum,
                    RPPrice = rp.RPPrice,
                    ProductId = rp.ProductId,
                    RefundAmoun = pr.RefundAmoun,
                    VendorId =v.VendorId
                }).ToList();

            // 3. 在内存中进行联接
            var list = (from dbData in vendorData
                          join product in products on dbData.ProductId equals product.ProductId
                          select new ListProcurementReturnDto
                          {
                              VName = dbData.VName,
                              PurchaseReturnsIds = dbData.PurchaseReturnsIds,
                              PurchaseReturnsCode = dbData.PurchaseReturnsCode,
                              PurchaseReturnsTopic = dbData.PurchaseReturnsTopic,
                              PReturnsPersonnel = dbData.PReturnsPersonnel,
                              ManpowerId = dbData.ManpowerId,
                              PRReturnDate = dbData.PRReturnDate,
                              PROutboundProgress = dbData.PROutboundProgress,
                              PRShipmentState = dbData.PRShipmentState,
                              PRReturnType = dbData.PRReturnType,
                              RPNum = dbData.RPNum,
                              RPPrice = dbData.RPPrice,
                              ProductId = dbData.ProductId,
                              RefundAmoun = dbData.RefundAmoun,
                              VendorId = dbData.VendorId,
                              PNumber = product.PNumber,
                              PName = product.PName,
                              PSpec = product.PSpec,
                              PUnit = product.PUnit
                          }).ToList();

            //退货编号
            if (!string.IsNullOrEmpty(request.PurchaseReturnsCode))
            {
                list = list.Where(p => p.PurchaseReturnsCode.Contains(request.PurchaseReturnsCode)).ToList();
            }
            //退货主题
            if (!string.IsNullOrEmpty(request.PurchaseReturnsTopic))
            {
                list = list.Where(p => p.PurchaseReturnsTopic.Contains(request.PurchaseReturnsTopic)).ToList();
            }
            //退货日期
            if (request.Pstart != null)
            {
                list = list.Where(p => p.PRReturnDate >= request.Pstart).ToList();
            }
            if (request.Pend != null)
            {
                list = list.Where(p => p.PRReturnDate < request.Pend).ToList();
            }
            //发货状态
            if (request.PRShipmentState != null)
            {
                list = list.Where(p => p.PRShipmentState == request.PRShipmentState).ToList();
            }
            //出库进展
            if (request.PROutboundProgress != null)
            {
                list = list.Where(p => p.PROutboundProgress == request.PROutboundProgress).ToList();
            }
            //供应商
            if (!string.IsNullOrEmpty(request.VName))
            {
                list = list.Where(p => p.VName.Contains(request.VName)).ToList();
            }
            
            PageDto<ListProcurementReturnDto> page = new PageDto<ListProcurementReturnDto>();
            page.lcount = list.Count();
            page.pcount = (int)Math.Ceiling(page.lcount * 1.0 / request.Psize);
            page.list = list.OrderByDescending(x => x.ManpowerId).Skip((request.Pindex - 1) * request.Psize).Take(request.Psize).ToList();
            return page;
        }

        /// <summary>
        /// 显示产品信息
        /// </summary>
        /// <param name="PName"></param>
        /// <param name="PNumber"></param>
        /// <param name="pindex"></param>
        /// <param name="psize"></param>
        /// <returns></returns>
        public async Task<dynamic> GetProductList(string? PName, string? PNumber, int pindex, int psize)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1MCIsInNpZCI6IjE4NjcwOTU3MzQ0NjIwNTg0OTYiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMTksMTkiLCJqdGkiOiI1MGYyMWRmZS0yNWQ3LTQ1OTQtOTg1Yi0wZTM2MDhhZjJiNmYiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi5LuY5rSb5ZiJIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvdXJpIjoiLyIsImlzcyI6IlJlbmFvYm8yMDA0IiwiYXVkIjoiV2VpZnV3dTIyMDNBIn0._wh23n1M7asMGST9NyeZj-5rk5ICAiOFv6yDk6e2o7Y";
            HttpClientWrapper cilent = new HttpClientWrapper(token);

            string chanpin = "http://116.205.121.197:8000/erpcp/api/Product/ProductShow?PName=" + PName + "&PNumber=" + PNumber + "&ProductTypeId=" + 0 + "&PageIndex=" + pindex + "&PageSize=" + psize;

            string postReponse = await cilent.GetAsync(chanpin);
            var json = JsonConvert.DeserializeObject<ApiResultList<Products>>(postReponse);
            return json.data.list;
        }


        //产品
        public class Products
        {
            /// <summary>
            /// 产品Id
            /// </summary>
            [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
            public int ProductId { get; set; }
            /// <summary>
            /// 标识
            /// </summary>

            public int? PCharacteristic { get; set; }
            /// <summary>
            /// 产品编号
            /// </summary>
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PNumber { get; set; }
            /// <summary>
            /// 产品名称
            /// </summary>
            /// 
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PName { get; set; }
            /// <summary>
            /// 规格型号
            /// </summary>
            /// 
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PSpec { get; set; }
            /// <summary>
            /// 单位
            /// </summary>
            /// 
            [SugarColumn(ColumnDataType = "Nvarchar(50)")]//设计长度
            public string? PUnit { get; set; }

            /// <summary>
            /// 产品分类ID
            /// </summary>

            public int ProductTypeId { get; set; }




        }
    }
}
